<template>
  <div>
    <el-upload
      :action="dataObj.host"
      :data="dataObj"
      :fileList="fileList"
      list-type="picture-card"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      :limit="maxCount"
      :on-exceed="handleExceed"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt/>
    </el-dialog>
  </div>
</template>
<script>
import { policy } from "./policy"
import { getUUID } from '@/utils'
import imageConversion from 'image-conversion'
export default {
  name: "multiUpload",
  props: {
    //图片属性数组
    value: Array,
    //最大上传图片数量
    maxCount: {
      type: Number,
      default: 30
    }
  },
  data() {
    return {
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
        uuid: ""
      },
      dialogVisible: false,
      dialogImageUrl: null,
      //压缩质量
      imgQuality: 0.5
    };
  },
  computed: {
    fileList() {
      let fileList = [];
      for (let i = 0; i < this.value.length; i++) {
        fileList.push({ url: this.value[i] });
      }
      return fileList;
    }
  },
  mounted() {},
  methods: {
    emitInput(fileList) {
      let value = [];
      for (let i = 0; i < fileList.length; i++) {
        value.push(fileList[i].url);
      }
      this.$emit("input", value);
      console.log(value);
    },
    handleRemove(file, fileList) {
      this.emitInput(fileList);
    },
    handlePreview(file) {
      this.dialogVisible = true;
      this.dialogImageUrl = file.url;
    },
    dataURItoBlob(dataURI, type) {
      var binary = atob(dataURI.split(',')[1]);
      var array = [];
      for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], {type: type});
    },

    beforeUpload(file) {
      let _self = this;
      return new Promise((resolve, reject) => {
        policy()
          .then(response => {
            console.log("这是什么${filename}");
            console.log(response)
            _self.dataObj.policy = response.data.policy;
            _self.dataObj.signature = response.data.signature;
            _self.dataObj.ossaccessKeyId = response.data.accessid;
            _self.dataObj.key = response.data.dir + "/"+getUUID()+"_${filename}";
            _self.dataObj.dir = response.data.dir;
            _self.dataObj.host = response.data.host;
            let isLt2M = file.size / 1024 / 1024 < 4 // 判定图片大小是否小于4MB
            if (!isLt2M) {
              imageConversion.compressAccurately(file, 500).then(res => { // console.log(res)
                resolve(res)
              })
            }else{
              const reader = new FileReader()
              const image = new Image()
              image.onload = (imageEvent) => {
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                const width = image.width * _self.imgQuality
                const height = image.height * _self.imgQuality
                canvas.width = width;
                canvas.height = height;
                context.clearRect(0, 0, width, height);
                context.drawImage(image, 0, 0, width, height);
                const dataUrl = canvas.toDataURL(file.type);
                const blobData = _self.dataURItoBlob(dataUrl, file.type);
                resolve(blobData)
              }
              reader.onload = (e => { image.src = e.target.result; });
              reader.readAsDataURL(file);
            }
          })
          .catch(err => {
            console.log("出错了...",err)
            reject(false);
          })


      });
    },
    handleUploadSuccess(res, file) {
      this.fileList.push({
        name: file.name,
        // url: this.dataObj.host + "/" + this.dataObj.dir + "/" + file.name； 替换${filename}为真正的文件名
        url: this.dataObj.host + "/" + this.dataObj.key.replace("${filename}",file.name)
      });

      this.emitInput(this.fileList);
      this.$http({
        url: this.$http.adornUrl(`/xqappserverthirdparty/unfiledresource/save`),
        method: 'post',
        data: this.$http.adornData({
          'resourceName': file.name,
          'resourceUrl': this.dataObj.host + "/" + this.dataObj.key.replace("${filename}",file.name),
          'resourceSize': file.size
        })
      }).then(({data}) => {
        if (data && data.code === 0) {

        } else {
          this.$message.error(data.msg)
        }
      })
    },
    handleExceed(files, fileList) {
      this.$message({
        message: "最多只能上传" + this.maxCount + "张图片",
        type: "warning",
        duration: 1000
      });
    }
  }
};
</script>
<style>
</style>


